package cn.jimmie.learn.pbc.base;

import android.content.res.AssetManager;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;

import cn.jimmie.learn.pbc.resource.Plugin;
import cn.jimmie.learn.pbc.resource.ShareInstance;

/**
 * function :
 *
 * <p> Create Time:  2019年02月12日 16:41 </p>
 * <p> @author Jimmie.Qian  </p>
 */
public class BaseActivity extends FragmentActivity {

    private Resources.Theme mPluginTheme;
    private boolean mUsePlugin = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        loadPluginResourceTheme();
    }

    @Override
    public AssetManager getAssets() {
        return needUse() ? plugin().getPluginAssetManager() : super.getAssets();
    }

    @Override
    public Resources getResources() {
        return needUse() ? plugin().getPluginResources() : super.getResources();
    }

    @Override
    public Resources.Theme getTheme() {
        return needUse() ? mPluginTheme : super.getTheme();
    }

    public void usePluginResource(boolean use) {
        mUsePlugin = use;
    }

    private boolean needUse() {
        return mUsePlugin &&
                plugin().available() &&
                mPluginTheme != null;
    }

    public void loadPluginResourceTheme() {
        try {
            mPluginTheme = plugin().getPluginResources().newTheme();
            mPluginTheme.setTo(getTheme());
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    private static Plugin plugin() {
        return ShareInstance.instance().getPlugin();
    }
}
